package edu.umb.cs.antmanager.manager;

import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

import edu.umb.cs.antmanager.common.AgentInterface;
import edu.umb.cs.antmanager.common.MachineStatus;
import edu.umb.cs.antmanager.common.RMIServerConnector;
import edu.umb.cs.antmanager.domain.TestType;
import static edu.umb.cs.antmanager.common.Constants.*;

public class AgentConnRunnable implements Runnable{
	private String agentName;
	private RMIManagerServer manager;
	private int taskType;
	private TestType test;
	
	public AgentConnRunnable(String agentName,RMIManagerServer manager, int taskType, TestType test){
		this.agentName = agentName;
		this.manager = manager;
		this.taskType = taskType;
		this.test = test;
	}

	@Override
	public void run() {
		AgentInterface agent = getAgentConnector(agentName);
		try {
			if(agent != null){
				if(taskType == TASK_TYPE_SHUTDOWN){
					System.out.println("Shutdown Agent "+agentName);
					agent.shutDown();
				}else if (taskType == TASK_TYPE_RESTART){
					System.out.println("Restart Agent "+agentName);
					agent.restart();
				}else if(taskType == TASK_TYPE_EXECUTE){
					System.out.println("Execute "+test.getName()+" on Agent "+agentName);
					agent.excuteTask(test, manager.getManagerHostName());
				}
				agent = getAgentConnector(agentName);
			}

			MachineStatus machineStatus = null;
			if(agent!=null){
				System.out.println("Get the status of Agent "+agentName);
				machineStatus = agent.getStatus();
			}
			String status = null;
			if(machineStatus != null) status = machineStatus.getStatus(); 
			manager.updateMachineStatus(agentName,status);
		} catch (RemoteException e) {
			// TODO Agent's registry is not accessible
			System.err.println("Machine "+agentName+" is offline");
		}
	}

	private AgentInterface getAgentConnector(String agentName) {
		try {
			return RMIServerConnector.createAgentConnector(agentName);
		} catch (RemoteException e) {
			System.err.println("Machine "+agentName+" is offline");
			// TODO Agent's registry is not accessible
		} catch (MalformedURLException e) {
			// TODO the URL used to access the agent is incorrect see
			// RMIServerConnector for details
		} catch (NotBoundException e) {
			System.err.println("Machine "+agentName+" is offline");
			// TODO the agent is not binded to the registry
		}
		return null;
	}

}
